package com.dean.service.impl;

import com.dean.entity.DeanResponse;
import com.dean.exception.DeanRuntimeException;
import com.dean.service.DeanScriptService;
import com.dean.service.support.AbstractDeanScriptService;
import com.dean.utils.FileUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dean
 * @version 1.0
 * @description: TODO
 * @date 2024/2/2 15:34
 */
public class DefaultScriptExecutor {
    private final static String GROOVY_EXTENSION = ".groovy";

    private final static String JAVASCRIPT_EXTENSION = ".js";

    public DeanResponse call(String filePath,Map<String,Object> parameters){
        return call(new File(filePath),parameters);
    }

    public DeanResponse call(File file,Map<String,Object> parameters){
        DeanScriptService service = null;
        if(file.getName().endsWith(GROOVY_EXTENSION)){
            service = new DeanGroovyClassService();
        } else if (file.getName().endsWith(JAVASCRIPT_EXTENSION)) {
            service = new DeanJavaScriptService();
        }else{
            DeanRuntimeException.throwException(996,"非法操作:");
        }
        return service.call(FileUtils.readFile(file,"UTF-8"),parameters);
    }

    public static void main(String[] args) {
        DefaultScriptExecutor  executor = new DefaultScriptExecutor();
        System.out.println(executor.call(new File(DeanGroovyClassService.class.getClassLoader().getResource("").getPath()+"scripts/hello.groovy"),new HashMap<>()));
    }

}
